package org.webshop.frontend.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.webshop.backend.dbchif.DbAccess;
import org.webshop.backend.exceptions.DbAccessFailureException;
import org.webshop.frontend.servlets.util.ServletUtil;

/**
 * Servlet implementation class IngredientAddServlet
 */
@WebServlet("/admin/ingredients/remove")
public class IngredientRemoveServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public IngredientRemoveServlet() {
    }


    /**
     * Serve the system manager a view for adding a ingredient
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("ingredientId");
        if (idStr == null) {
            ServletUtil.showGeneralError("Ingredient id must be given", request, response);
            return;
        }
        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException ex) {
            ServletUtil.showGeneralError("Illegal ingredient id", request, response);
            return;
        }
        try {
            DbAccess.getInstance().removeIngredient(id);
        } catch (DbAccessFailureException ex) {
            ServletUtil.showGeneralError("Error with database", request, response);
            log(null, ex);
            return;
        }
        ServletUtil.redirect(response, "/webshop/admin/ingredients");
    }

    /**
     * Handle the request to add an ingredient by using the given data
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
